// ActionScript file
import Modules.Windows.AdminWindow;
import Modules.Windows.ValidationErrorWin;

import com.desidea.common.CommonClass;
import com.desidea.common.CustomFormatter;
import com.desidea.components.grid.button.SuperGridButton;
import com.desidea.components.spinner.BusySpinner;
import com.desidea.utils.DirtyChecker;
import com.desidea.utils.DisplayModeSetter;
import com.desidea.webservice.PartnerService;
import com.desidea.webservice.ProcessServiceRequestResultEvent;

import mx.controls.Alert;
import mx.controls.LinkButton;
import mx.core.Application;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;
import mx.utils.StringUtil;
import mx.validators.Validator;

private var _btnEditCancel:LinkButton;
private var _key:String = "";
private var _mode:String = "view";//Constants.MODE_ADD;
private var _modeSet:Boolean = false;
private var _creationCompleted:Boolean = false;
private var padetails:XML;

public function get mode():String{
	return _mode;
}

public function set mode(value:String):void{
	this._mode = value;
	this._modeSet = true;
}

public function get key():String{
	return _key;
}

public function set key(value:String):void{
	this._key = value;
}


private function windowCreated():void{

	_btnEditCancel = new LinkButton();
	_btnEditCancel.label = "Edit";	
	_btnEditCancel.height = this.pnlResellerAccountInfo.ToolBox.height - 2;
	_btnEditCancel.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('editdetails'); });
	this.pnlResellerAccountInfo.ToolBox.addChild(_btnEditCancel);
	this._creationCompleted = true;
	this.loadData();
}

private function setScreenMode():void{
	if(!_creationCompleted) return;
	
	if(this.mode == SuperGridButton.MODE_VIEW || mode == SuperGridButton.MODE_VIEWICON){
		DisplayModeSetter.getInstance().setMode(this.frmAccountInfo,false);
		btnSubmit.enabled = false;
		this.lblTitle.text = "View Reseller Account Details";
	}else if(this.mode == SuperGridButton.MODE_EDIT){		//MODE_EDIT = create new
		DisplayModeSetter.getInstance().setMode(this.frmAccountInfo,true);
		btnSubmit.enabled = true;
		_btnEditCancel.enabled = false;
		this.lblTitle.text = "New Reseller Account";
	}
}


private function init():void{
	this.txtNotes.linkTextInput.visible = false;
	this.txtNotes._RichTextEditor_VRule2.visible = false;
}

private function onClick(mode:String):void{
	switch(mode){
		case "editdetails":
			DisplayModeSetter.getInstance().setMode(this.frmAccountInfo,true);
			btnSubmit.enabled = true;
			_btnEditCancel.enabled = false;
			this.lblTitle.text = "Edit Reseller Account Details";
			break;
		case "openurl":
			navigateToURL( new URLRequest(this.txtWebsite.text),"_blank");
			break;
	}
}

private function buttonClick(eventType:String):void{
	switch(eventType){
		case "save":
			handleSubmitClick();
			break;
		case "cancel":
			handleCancelClick();
			break;
		default:
			Alert.show( "Yet to Implement : " + eventType);
	}
}

private function handleCancelClick():void{
	CommonClass.NextEvent = null;

	var win:AdminWindow = this.parentDocument as AdminWindow;
	var obj:Object = new Object();
	obj.id = CommonClass.SelectedMenuCode;
	win.data = obj; 
	win.loadModule();
}

private function handleSubmitClick():void{
	if(validate()){
		saveData("", getPostData());
	}else{
		CommonClass.NextEvent = null;
	}
}


private function loadData():void{
	
	if(this._creationCompleted && this._modeSet){
		//TODO: Call HTTP SERVICE TO LOAD THE DATA.

		var params:String = "OPERATION=RESELLERACCOUNT_GETDETAILS";

		switch(mode){
			case "new":
				break;
			case SuperGridButton.MODE_EDIT:
			case SuperGridButton.MODE_VIEW:
			case SuperGridButton.MODE_VIEWICON:
				params += "&PKID="+ escape(StringUtil.trim(this.key));
				break;
		}
			
		var ws:PartnerService = new PartnerService();
		ws.addprocessServiceRequestEventListener(callForResellerDetails);
		ws.processServiceRequest(params);					
	}
}

private function callForResellerDetails(event:ProcessServiceRequestResultEvent):void{
	padetails = XML(event.result);

	if(padetails.RESPONSE.RESULT == "E"){
		BusySpinner.getInstance().play(Application.application.ModuleCvs);
		Alert.show(padetails.RESPONSE.MESSAGE);
	}else if(padetails.RESPONSE.RESULT == 'S'){
		setDataOnControls(padetails);
		setScreenMode();
		this.callLater(initializeForDirtyCheck);
	}
}

private function setDataOnControls(response:XML):void{
	cmbState.dataProvider = new XML(response.STATES).entry as XMLList;
	cmbState.selectedIndex = 0;
	cmbState.selectedItem = (response.STATES.entry.(@id == response.STATE)[0]) as XML

	cmbRefSource.dataProvider = new XML(response.REFSOURCES).entry.(@id!="8") as XMLList;
	cmbRefSource.selectedIndex = 0;
	cmbRefSource.selectedItem = (response.REFSOURCES.entry.(@id == response.REFSOURCEID)[0]) as XML
	
	CommonClass.setDataOnComponents(this.txtResellerAccountName, response);
	CommonClass.setDataOnComponents(this.txtAddress, response);
	CommonClass.setDataOnComponents(this.txtCity, response);
	CommonClass.setDataOnComponents(this.txtZipCode, response);
	CommonClass.setDataOnComponents(this.txtTelephoneNo, response);
	CommonClass.setDataOnComponents(this.txtFaxNo, response);
	CommonClass.setDataOnComponents(this.txtWebsite, response);
	CommonClass.setDataOnComponents(this.txtWebsiteDescription, response);
	CommonClass.setDataOnComponents(this.txtNotes, response);
	CommonClass.setDataOnComponents(this.chkActive, response);

	txtTelephoneNo.text = CustomFormatter.getInstance().convertToPhoneString(txtTelephoneNo.text);
	txtFaxNo.text = CustomFormatter.getInstance().convertToPhoneString(txtFaxNo.text);

}


private function getPostData():String{

	txtTelephoneNo.text = CustomFormatter.getInstance().convertToPhoneString(txtTelephoneNo.text);
	txtFaxNo.text = CustomFormatter.getInstance().convertToPhoneString(txtFaxNo.text);

	var postData:String = new String();
	postData += "RESELLERACCOUNTNO=" + (padetails.RESELLERACCOUNTNO.toString())		+ "&";
	postData += "RESELLERACCOUNTGUID=" + (padetails.RESELLERACCOUNTGUID.toString())	+ "&";
	postData += "ADDRESSNO=" + (padetails.ADDRESSNO.toString())					+ "&";
	postData += "ADDRESSGUID=" + (padetails.ADDRESSGUID.toString())				+ "&";
	postData += "COMMUNICATIONID=" + (padetails.COMMUNICATIONID.toString())		+ "&";
	postData += "USERID=" + (CommonClass.UserID)								+ "&";
	postData += "NOTEID=" + (padetails.NOTEID.toString())						+ "&";
	
	postData += (CommonClass.preparePostString(this.txtResellerAccountName))	+ "&";
	postData += (CommonClass.preparePostString(this.cmbRefSource))				+ "&";
	postData += (CommonClass.preparePostString(this.txtAddress))				+ "&";
	postData += (CommonClass.preparePostString(this.txtCity))					+ "&";
	postData += (CommonClass.preparePostString(this.cmbState))					+ "&";
	postData += (CommonClass.preparePostString(this.txtZipCode))				+ "&";
	postData += (CommonClass.preparePostString(this.txtTelephoneNo))			+ "&";
	postData += (CommonClass.preparePostString(this.txtFaxNo))					+ "&";
	postData += (CommonClass.preparePostString(this.txtWebsite))				+ "&";
	postData += (CommonClass.preparePostString(this.txtWebsiteDescription))		+ "&";
	postData += (CommonClass.preparePostString(this.txtNotes))					+ "&";
	postData += (CommonClass.preparePostString(this.chkActive));

	return postData;	
}


private function saveData(action:String, data:String=""):void{
	BusySpinner.getInstance().play(Application.application.ModuleCvs);
	var params:String = "OPERATION=RESELLERACCOUNT_UPDATEDETAILS" +
						//"&PKID="+this.key+
						(data.length>0?"&":"") +data;
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForUpdateResellerDetails);
	ws.processServiceRequest(params);
}


private function callForUpdateResellerDetails(event:ProcessServiceRequestResultEvent):void{
	
	var response:XML = XML(event.result);

	BusySpinner.getInstance().stop();

	if(response.RESPONSE.RESULT == "S"){
		DirtyChecker.getInstance().resetDirtyChecker();
		
		if(CommonClass.NextEvent != null && CommonClass.NextEvent is Button)
			(CommonClass.NextEvent as Button).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		else
			handleCancelClick();
	}else{
		Alert.show( String(response.RESPONSE.MESSAGE),"Save Error" );	
	}	
	
}

private function validate():Boolean {
	var v:Array = new Array();
	v.push(nameV,addressV,cityV);
	v.push(stateV, zipV, phoneV, faxV);
	
	var result:Array = Validator.validateAll(v);

	if(result.length>0){
		var vWin:ValidationErrorWin = new ValidationErrorWin();
		vWin.Messages = result;
		vWin.title = "Save : Reseller Account Details";
		
		PopUpManager.addPopUp(vWin,this,true);
		PopUpManager.centerPopUp(vWin);
		return false;
	}
	return true;
}

private function initializeForDirtyCheck():void{
	BusySpinner.getInstance().stop();
	DirtyChecker.getInstance().setInitialControl(this);
}

public function promptToSave():void{
	Alert.buttonWidth = 110;
	var yesNoCancelAlert: Alert = Alert.show("Do you want to save before exiting?", "Save",Alert.YES | Alert.NO | Alert.CANCEL, Application.application.ModuleCvs,performAlertAction);
}

private function performAlertAction(event:CloseEvent):void{
	if(event.detail == Alert.YES){
		handleSubmitClick();
	}else if(event.detail == Alert.NO){
		DirtyChecker.getInstance().resetDirtyChecker();
		if(CommonClass.NextEvent != null && CommonClass.NextEvent is Button)
			(CommonClass.NextEvent as Button).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		else
			handleCancelClick();
	}else{
		// PERFORM NO ACTION - STAY BACK TO THE PAGE
	}
}